package com.yb.handler;

import javax.management.RuntimeErrorException;

public class Looper {
	MessageQueue mQueue;
	static ThreadLocal<Looper> sThreadLocal = new ThreadLocal();
	
	
	/**
	 * 初始化Looper对象
	 * 一个线程只能关联一个Looper对象
	 */
	public static void prepare(){
		if (sThreadLocal.get() != null) {
			throw new RuntimeErrorException(null, "不能重复获取Looper");
		}
		sThreadLocal.set(new Looper());
	}
	
	/**
	 * 获取当前线程的Looper
	 * @return
	 */
	public static Looper myLooper(){
		return sThreadLocal.get();
	}
	
	/**
	 * 轮询消息
	 */
	public static void loop() {
		Looper looper = myLooper();
		MessageQueue queue = looper.mQueue;
		
		for(;;){
//			queue.next();
			Message msg = queue.next();
			if (msg == null) {
				continue;
			}
			msg.target.dispatchMessage(msg);
		}
		
	}
	
	private Looper(){
		mQueue  = new MessageQueue();
	}
}
